﻿using Grpc.Net.Client.Balancer;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Nacos.Provider.gRPC
{
    public class NacosRandomBalancer : SubchannelsLoadBalancer
    {
        public NacosRandomBalancer(IChannelControlHelper controller, ILoggerFactory loggerFactory)
          : base(controller, loggerFactory)
        {
        }

        protected override SubchannelPicker CreatePicker(IReadOnlyList<Subchannel> readySubchannels)
        {
            return new RandomPicker(readySubchannels);
        }

        private class RandomPicker : SubchannelPicker
        {
            private readonly IReadOnlyList<Subchannel> subchannels;

            public RandomPicker(IReadOnlyList<Subchannel> subchannels)
            {
                this.subchannels = subchannels;
            }

            public override PickResult Pick(PickContext context)
            {
                return PickResult.ForSubchannel(subchannels[new Random().Next(0, subchannels.Count)]);
            }
        }
    }
}
